package com.cos.hospital.ui.patient;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.code.Logic;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.AcupointBean;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.LastRecordInfo;
import com.cos.hospital.model.bean.PatientFile;
import com.cos.hospital.model.bean.PatientInfo;
import com.cos.hospital.model.bean.PatientInfoBean;
import com.cos.hospital.model.bean.RecordTRInfo;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.model.event.PatientInfoEditEvent;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.UDate;
import com.cos.hospital.tool.URegular;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.patient.compare.CompareActivity;
import com.cos.hospital.ui.record.RecordEditActivity;
import com.cos.hospital.ui.record.adapter.AdapterAcupoint;
import com.cos.hospital.widget.MultImageView;
import com.cos.hospital.widget.MyGridLayoutManager;
import com.cos.hospital.widget.MySpaceDecoration;
import com.cos.hospital.widget.ProgressDialog;
import com.google.gson.JsonObject;
import com.jude.utils.JUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 患者档案
 */
public class PatientInfoActivity extends BaseActivity {
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_gender)
    TextView tv_gender;
    @BindView(R.id.tv_age)
    TextView tv_age;
    @BindView(R.id.tv_medicalNum)
    TextView tv_medicalNum;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_IDCard)
    TextView tv_IDCard;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.ll_diagnose)
    LinearLayout ll_diagnose;
    @BindView(R.id.tv_diagnose_time)
    TextView tv_diagnose_time;
    @BindView(R.id.tv_diagnose)
    TextView tv_diagnose;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.tv_num)
    TextView tv_num;
    @BindView(R.id.tv_cure_time)
    TextView tv_cure_time;
    @BindView(R.id.rc)
    RecyclerView rc;
    @BindView(R.id.other_treat)
    TextView otherTreat; // 其他治疗

    @BindView(R.id.mult_image_view)
    MultImageView imageView;
    //处方
    @BindView(R.id.tv_prescription)
    TextView tv_Prescription;
    private List<AcupointBean> list;
    private BaseQuickAdapter adapter;
    private int fldPatientId;
    private int fldMedicalHistoryId;
    private int fldState;//患者签到状态，0：无状态，1：候诊中（患者签到），2：已接诊（患者已接诊）
    private int fldSignId;//签到ID
    private PatientFile patientFile;

    @Override
    protected int layout() {
        return R.layout.activity_patient_info;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        fldPatientId = intent.getIntExtra(Code.SP.ID, 0);
        fldMedicalHistoryId = intent.getIntExtra(Code.SP.FLDMEDICALHISTORYID, 0);
        fldState = intent.getIntExtra(Code.SP.FLDSTATE, 0);
        fldSignId = intent.getIntExtra(Code.SP.FLDSIGNID, 0);
        setTitleLeftIcon();
        setTitleCenterTxt("患者档案");
        list = new ArrayList<>();
        adapter = new AdapterAcupoint(list);
        adapter.openLoadAnimation();
        MyGridLayoutManager myGridLayoutManager = new MyGridLayoutManager(context, 4);
        myGridLayoutManager.setScrollEnabled(false);
        rc.setLayoutManager(myGridLayoutManager);
        rc.addItemDecoration(new MySpaceDecoration(JUtils.dip2px(10)));
        rc.setAdapter(adapter);
    }

    @Override
    protected void logic() {
        getInfo();
    }

    private void getInfo() {
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", fldPatientId);
        UHttp.start(getServes().patientFileSearch(jsonObject), "患者档案查询", new HttpMsgListener<ResultBean<PatientFile>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<PatientFile> dto) {
                if (dto.isSuccess()) {
                    patientFile = dto.getResult();
                    showPatientInfo();
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void showPatientInfo() {
        if (patientFile == null) {
            return;
        }
        PatientInfo patientInfo = patientFile.getPatientInfo();
        if (patientInfo != null) {
            tv_name.setText(patientInfo.getFldName());
            tv_gender.setText(Logic.getSex(patientInfo.getFldSex()));
            tv_age.setText(patientInfo.getFldAge() + "岁");
            tv_medicalNum.setText(patientInfo.getFldMedicalNum());
            tv_phone.setText(URegular.formPhoneNo(patientInfo.getFldPhone()));
            tv_IDCard.setText(URegular.formIDCardNo(patientInfo.getFldIdCardNo()));
            tv_address.setText(patientInfo.getFldAddress());
        }


        LastRecordInfo lastRecordInfo = patientFile.getLastRecordInfo();
        if (lastRecordInfo != null) {
            String fldDiagnose = lastRecordInfo.getFldDiagnose();
            if (UTxt.isEmpty(fldDiagnose)) {
                ll_diagnose.setVisibility(View.GONE);
                tv_diagnose_time.setText("无");
            } else {
                ll_diagnose.setVisibility(View.VISIBLE);
                tv_diagnose_time.setText(UDate.strToStrSafety(lastRecordInfo.getFldCreateTime(), "yyyy-MM-dd"));
                tv_diagnose.setText(fldDiagnose);
            }
            String fldTreamentTime = lastRecordInfo.getFldTreamentTime();
            if (fldTreamentTime == null) {
                tv_cure_time.setText("无");
            } else {
                tv_cure_time.setText(UDate.strToStrSafety(fldTreamentTime, "yyyy-MM-dd"));
            }
            otherTreat.setText(TextUtils.isEmpty(lastRecordInfo.getFldTreatmentDesc()) ? "无" : lastRecordInfo.getFldTreatmentDesc());
            List<AcupointBean> acupointBeanList = lastRecordInfo.getRecordAcutionInfo();
            list.clear();
            if (!UTxt.isEmpty(acupointBeanList)) {
                list.addAll(acupointBeanList);
            }
            adapter.notifyDataSetChanged();
            RecordTRInfo recordTRInfo = lastRecordInfo.getRecordTRInfo();
            if (recordTRInfo != null) {
                tv_Prescription.setText(recordTRInfo.getTR_content());
                ArrayList<String> arrayList = new ArrayList<>();
                for (int i = 0; i < recordTRInfo.getString().size(); i++) {
                    String s = recordTRInfo.getString().get(i);
                    arrayList.add(Code.Link.HOST_URL + s);
                }
                imageView.setImages(arrayList);
            }

        }


        List<PatientInfoBean.CureBean> cureBeanList = patientFile.getTreatementItemInfo();
        int total = 0;
        int surplus = 0;
        if (!UTxt.isEmpty(cureBeanList)) {
            for (PatientInfoBean.CureBean cureBean : cureBeanList) {
                surplus += cureBean.getFldNum();
                total += cureBean.getFldTotalNum();
            }
        }
        progressbar.setMax(total);
        progressbar.setProgress(surplus);
        tv_num.setText(surplus + " / " + total);
    }

    @OnClick({R.id.title_back, R.id.ll_patient_info, R.id.ll_surplus_cure, R.id.ll_history_records, R.id.tv_contrast, R.id.tv_write, R.id
            .tv_reception})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.ll_patient_info:
                toEditInfo();
                break;
            case R.id.ll_surplus_cure:
                toSurplusCure();
                break;
            case R.id.ll_history_records:
                toHistoryRecords();
                break;
            case R.id.tv_contrast://对比病历:
                if (patientFile == null || fldPatientId == 0) {
                    showNotice("数据异常");
                    return;
                }
                Intent intentCompare = new Intent(this, CompareActivity.class);
                intentCompare.putExtra(Code.SP.ID, fldPatientId);//患者ID
                intentCompare.putExtra("user_name", patientFile.getPatientInfo().getFldName());
                intentCompare.putExtra("user_sex", patientFile.getPatientInfo().getFldSex());
                intentCompare.putExtra("user_age", patientFile.getPatientInfo().getFldAge());
                intentCompare.putExtra("user_avator", "");
                startActivity(intentCompare);
                break;
            case R.id.tv_write:
                writeRecords();
                break;
            case R.id.tv_reception:
                if (fldState == 2) {//患者签到状态，0：无状态，1：候诊中（患者签到），2：已接诊（患者已接诊）
                    Intent intent = new Intent(context, RecordEditActivity.class);
                    intent.putExtra(Code.SP.ID, fldMedicalHistoryId);
                    startActivity(intent);
                    finish();
                    return;
                }
                reception();
                break;
        }
    }

    private void reception() {
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldPatientId", fldPatientId);
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("fldEditId", SPUtil.getUserId());
        jsonObject.addProperty("fldMedicalFlag", 0);//初复诊标识 初诊 = 0,复诊 = 1
        if (fldSignId != 0) {
            jsonObject.addProperty("fldSignId", fldSignId);
        }
        UHttp.start(getServes().saveMedical(jsonObject), "病历保存(可同时签到接诊)", new HttpMsgListener<ResultBean<Integer>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<Integer> dto) {
                if (dto.isSuccess()) {
                    Intent intent = new Intent(context, RecordEditActivity.class);
                    intent.putExtra(Code.SP.ID, dto.getResult());
                    startActivity(intent);
                    finish();
                    sendBroadcast(new Intent(Code.Broadcast.CutoverToReception));
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void writeRecords() {
        Intent intent = new Intent(this, ReplenishRecordsTimeActivity.class);
        intent.putExtra(Code.SP.ID, fldPatientId);
        startActivity(intent);
    }

    private void toEditInfo() {
        if (patientFile == null) {
            USnackbar.showError(this, "未加载到患者信息");
            return;
        }
        Intent intent = new Intent(this, PatientEditActivity.class);
        intent.putExtra(Code.SP.KEY, patientFile.getPatientInfo());
        startActivity(intent);
    }

    private void toSurplusCure() {
        Intent intent = new Intent(this, SurplusCureActivity.class);
        intent.putExtra(Code.SP.ID, fldPatientId);
        startActivity(intent);
    }

    private void toHistoryRecords() {
        Intent intent = new Intent(this, HistoryRecordsActivity.class);
        intent.putExtra(Code.SP.ID, fldPatientId);
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateInfo(PatientInfoEditEvent event) {
        getInfo();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
